/**
* 用户详情对话框（可用于添加和修改对话框）
*/
var ActivityInfoDlg = {
    width: '650px',
    height: '850px',
    currentLayerIndex: -1,
    cache: "",
    InfoData: {},
    courseTableData: [],
    activityId: "",
    selectItemList: []
};

/**
 * 初始化新增弹出框
 */
ActivityInfoDlg.init = function () {
    this.cache = $("#activityDialog").html();

    // alert($(":radio[name='discount']:checked").val());
    // $(":radio[name='discount']").click(function () {
    //     if($(":radio[name='discount']:checked").val()=="1"){
    //         $("#discount1").text("折");
    //     }
    //     else{
    //         $("#discount1").text("元");
    //     }
    // });

    $("#activityDialog").html('');
};

/**
 * 清除数据
 */
ActivityInfoDlg.clearData = function () {
    this.InfoData = {};
    this.courseTableData = [];
};

/**
 * 关闭此对话框
 */
ActivityInfoDlg.close = function () {
    layer.close(this.currentLayerIndex);
    ActivityInfoDlg.clearData();
};

/**
 * 新增打开模态框调用事件
 */
ActivityInfoDlg.renderAdd = function (index) {
    //初始化icheck选中样式
    initICheck();

    ActivityInfoDlg.initSearchCourses();
    ActivityInfoDlg.select2Change();
    initDatePicker();

    $('input').on('ifChecked', function(event){
        var val = $("[name='discountType']:checked").val();
        if(val==="1"){
            $(".discount").html("折扣程度");
            $("#discount").attr("placeholder","请输入折扣程度");
            $("#discountUnit").text("折");
        }
        else{
            $(".discount").html("一口价");
            $("#discount").attr("placeholder","请输入一口价");
            $("#discountUnit").text("元");
        }
    });
};
/**
 * 新增
 */
ActivityInfoDlg.addSubmit = function (index) {
    var options = $("#frmMain").serialize();
    var courseData = ActivityInfoDlg.courseTableData;
    for (var i in courseData) {
        for (var j in courseData[i]) {
            options += "&courseList[" + i + "]." + j + "=" + courseData[i][j];
        }
    }
    // 提交信息
    var ajax = new $ax(Feng.ctxPath + "/activity/save", function (data) {
        if (data.success) {
            Feng.success("添加成功!");
            layer.close(index);
            ActivityTable.me.refresh();
        } else if (data.code === 2) {
            Feng.error(data.msg);
        } else {
            Feng.error("添加失败!");
        }
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.setData(options);
    ajax.start();
};

/**
 * 编辑
 */
ActivityInfoDlg.load = function (id) {
    var ajax = new $ax(Feng.ctxPath + "/activity/getById", function (data) {
        Feng.log("活动信息查询成功");
        if (data.success){
            var activity = data.obj || null;
            //显示活动信息
            for (var i in activity) {
                //判断Id与name是否相同
                if ($("#" + i).attr("name") === i) {
                    $("#" + i).val(activity[i]);
                }
            }
            //显示活动类型
            if (activity.activityType === "1") {
                $('#activityType').iCheck('check');
            }
            else {
                $('#activityType').iCheck('check');
            }
            //显示折扣类型
            if (activity.discountType === "1") {
                $('#discountType1').iCheck('check');
            }
            else {
                $('#discountType2').iCheck('check');
            }

            //显示课程信息
            if (activity !== null) {
                ActivityInfoDlg.courseTableData = activity.courseList;
                ActivityInfoDlg.refresh();
            }
        }
    },function(data){
        Feng.error("加载信息失败!");
    });
    ajax.data={id:id};
    ajax.start();
};


/**
 * 提交修改
 */
ActivityInfoDlg.editSubmit = function () {
    var options = $("#frmMain").serialize();
    var courseData = ActivityInfoDlg.courseTableData;
    for (var i in courseData) {
        for (var j in courseData[i]) {
            if(j == "activityId" || j == "courseId"){
                options += "&courseList[" + i + "]." + j + "=" + courseData[i][j];
            }
        }
    }
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/activity/update", function (data) {
        if (data.success) {
            Feng.success("修改成功!");
            ActivityTable.me.refresh();
        } else if (data.code === 2) {
            Feng.error(data.msg);
        } else {
            Feng.error("修改失败!");
        }
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.setData(options);
    ajax.start();
};

// 初始化课程select
ActivityInfoDlg.initSearchCourses = function(){
    $("#course").select2({
        ajax: {
            type:'post',
            url: Feng.ctxPath+ "/course/allParam",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    courseName: params.term, // search term 请求参数 ， 请求框中输入的参数
                    hasBinding: 'notBind',
                    current:1,
                    size:999
                };
            },
            processResults: function (data, params) {
                params.page = data.size || 1;
                var itemList = [];//当数据对象不是{id:0,text:'ANTS'}这种形式的时候，可以使用类似此方法创建新的数组对象
                var arr = data.records;
                for(item in arr){
                    itemList.push({
                        id: arr[item].id,
                        courseId: arr[item].id,
                        text: arr[item].courseName,
                        coursePrice: arr[item].coursePrice,
                        courseEndDate: arr[item].courseEndDate
                    })
                }
                return {
                    results: itemList
                };
            },
            cache: true
        },
        // multiple: true,
        placeholder: "输入课程名称搜索",
        language: "zh-CN",
        // tags: true,//允许手动添加
        allowClear: true,//允许清空
        escapeMarkup: function (markup) { return markup; }, // 自定义格式化防止xss注入
        minimumInputLength: 2,//最少输入多少个字符后开始查询
        templateResult: function templateResult(repo){
            // console.log(repo);
            return repo.text;
            }, // 函数用来渲染结果
        templateSelection: function templateSelection(repo){
            // console.log(repo);
            return repo.text;
        } // 函数用于呈现当前的选择
    });
};


ActivityInfoDlg.select2Change = function () {
    $("#course").change(function(){
        var courseSelect = $("#course").select2("data")[0];
        var course = {
            id:courseSelect.id,
            courseId: courseSelect.id,
            courseName: courseSelect.text,
            coursePrice: courseSelect.coursePrice,
            courseEndDate: courseSelect.courseEndDate
        };
        ActivityInfoDlg.courseTableData.push(course);
        //刷新表格
        console.log(course);
        ActivityInfoDlg.refresh();
    });
};

//刷新列表
ActivityInfoDlg.refresh = function () {
    var outHtml = template("dataInspectionContentTmpl", this.courseTableData);
    $("#courseTableBody").html(outHtml);
};
//删除列表
ActivityInfoDlg.deleteCourse = function (val) {
    for (var i = 0; i < this.courseTableData.length; i++) {
        if (this.courseTableData[i].courseId == val) {
            this.courseTableData.splice(i, 1);
            break;
        }
    }
    ActivityInfoDlg.refresh();
};


$(document).on("click","#discountType .control-label",function () {
    alert();
    $(".discount").hide();
    $(".discount").eq($(this).val()-1).show();
});

$('input[type=radio][name=discountType]').change(function () {
    alert("Allot Thai Gayo Bhai");
    if (this.value == '1') {
        alert("Allot Thai Gayo Bhai");
    }
    else if (this.value == '2') {
        alert("Transfer Thai Gayo");
    }
});

/**
 * 点击批量绑定按钮时，跳出批量绑定对话框
 * @returns
 */
function clickBatchBtn(){
    ActivityBatchInfoDlg.clearData();
    var index = layer.open({
        type: 1,
        title: '批量添加课程',
        skin: 'layui-layer-lan', //加上边框
        area: [ActivityBatchInfoDlg.width, 'auto'],//宽高
        content: ActivityBatchInfoDlg.cache,
        success: function(layero, index){
            //层弹出成功后回调方法
            ActivityBatchInfoDlg.renderAdd();
        },
        maxmin:true,
        scrollbar: false,
        btn:['保存','关闭'],
        btnAlign: 'r',  //默认值
        yes:function (index,layero) {
            var activityId = ActivityInfoDlg.activityId;
            ActivityBatchInfoDlg.batchBindSubmit(activityId);
            if(activityId !== ""){
                ActivityInfoDlg.load(ActivityInfoDlg.activityId);
            }else{
                var arr = ActivityBatchInfoDlg.selectData;
                    for(item in arr){
                        if(contains(ActivityInfoDlg.selectItemList,arr[item])){
                            Feng.error("请不要重复选择课程")
                        }else{
                            ActivityInfoDlg.selectItemList.push({
                                id:arr[item].id,
                                courseId: arr[item].id,
                                courseName: arr[item].courseName,
                                coursePrice: arr[item].coursePrice,
                                courseEndDate: arr[item].courseEndDate
                            })
                        }

                    }
                ActivityInfoDlg.courseTableData = ActivityInfoDlg.selectItemList;
            }
            ActivityInfoDlg.refresh();
            layer.close(index); //如果设定了yes回调，需进行手工关闭
        },btn2:function (index) {
            layer.close(index);
        },
        cancel:function (index, layero) {
            //右上角关闭按钮触发的回调
            layer.close(index);
        }
    });
    layer.full(index);
    ActivityBatchInfoDlg.currentLayerIndex = index;
}

function contains(arr, obj) {
    var i = arr.length;
    while (i--) {
        if (arr[i].id === obj.id) {
            return true;
        }
    }
    return false;
}


